<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class CategoryController extends CommonController
{
    public function getIndex()
    {
        $lists = Category::with('pCategory')->orderBy('id','asc')->paginate(10);
        return view('category.index')->with("lists",$lists)->with('actions',$this->actions);
    }
    public function postDelete(Request $request)
    {
        $id = $request->input('cid');
        Category::where('id',$id)->delete();
        Category::cache(1);
        return AjaxCallbackMessage('恭喜，删除成功', true, url('category/index'));
    }
    public function getEdit(Request $request)
    {
        $data = $request->input();
        $lists = Category::with('pCategory')->orderBy('id','asc')->get();
        $me = Category::where('id',$data['id'])->first();

        $family = subTree($lists,$data['id']);

        $others = array();
        foreach($lists as $k => $v)
        {
            if(!in_array($v,$family) && $v->id != $me->id){
                $others[]=$v;
            }
        }
        return view('category.edit')->with('others',$others)->with('me',$me);
    }
    public function postEdit(Requests\CategoryRequest $request)
    {
        $data = $request->input();
        $id = $data['id'];
        unset($data['id'],$data['_token'],$data['formType']);
        Category::where('id',$id)->update($data);
        Category::cache(1);
        return AjaxCallbackMessage('恭喜，修改成功',true,url('category/index'));
    }
    public function getCreate()
    {
        $lists = Category::with('pCategory')->oderBy('id','asc')->get();
        return view('category.create')->with("lists",$lists);
    }
    public function search(Request $request)
    {
        $data = $request->input();
        $sql = Category::with('pCategory')->orderBy('id','asc');
        if(isset($data['name']) && $data['name'] !=''){
            $sql->where('name','like','%'.trim($data['name'].'%'));
        }
        if(isset($data['recommend']) && $data['recommend'] !=''){
            $sql->where('recommend','like','%'.trim($data['recommend'].'%'));
        }
        if(isset($data['status']) && $data['status'] !=''){
            $sql->where('staus','like','%'.trim($data['staus'].'%'));
        }
        $lists = $sql->paginate(10);
        return view('category.search')->with('lists',$lists)->with("name", $data['name'])
            ->with("recommend", $data['recommend'])->with("status", $data['status'])
            ->with("hot", $data['hot'])->with("actions", $this->actions);
    }
}
